import * as systemService from '../services/system';
import {routerRedux} from 'dva/router';
import queryString from 'query-string';

export default {
  namespace: 'main',
  state: {
    selectedKey: '',
    openSubMenKey: '',
    locationPathname: '',
    locationQuery: {},
  },
  reducers: {
    setSelectedKey(state, {payload}) {
      window.localStorage.setItem("mf-selectedKeyPayload", JSON.stringify(payload));
      const newState = state;
      newState.selectedKey = payload.key + '';
      newState.openSubMenKey = payload.parentId + '';
      return newState;
    },
    updateState(state, {payload}) {
      const newstate = state;
      if ('/login' != payload.locationPathname && null != payload.locationPathname && '' != payload.locationPathname.trim() && '/' != payload.locationPathname.trim()) {
        newstate.locationPathname = payload.locationPathname;
        window.localStorage.setItem("mf-locationPathname", JSON.stringify(payload.locationPathname));
        newstate.locationQuery = payload.locationQuery;
      }
      return newstate;
    },
  },
  effects: {
    *getResource({payload},{call, put}) {
      const {data} = yield call(systemService.getResource);
      window.sessionStorage.setItem("resources", JSON.stringify(data));

      const hislocationPathname = JSON.parse(window.localStorage.getItem("mf-locationPathname"));
      const selectedKeyPayload = window.localStorage.getItem("mf-selectedKeyPayload");
      if (null != selectedKeyPayload && null != hislocationPathname) {
        const str = JSON.stringify(data);
        if (str.indexOf(hislocationPathname) > -1) {
          const pay = JSON.parse(selectedKeyPayload);
          yield  put({
            type: 'setSelectedKey',
            payload: pay
          });
          yield put(routerRedux.push(hislocationPathname));
        } else {
          yield  put({
            type: 'setSelectedKey',
            payload: {
              selectedKey: null,
              openSubMenKey: null,
            }
          });
          yield put(routerRedux.push('/dashBoard'));
        }

      } else {
        yield  put({
          type: 'setSelectedKey',
          payload: {
            selectedKey: null,
            openSubMenKey: null,
          }
        });
        yield put(routerRedux.push('/dashBoard'));
      }
    },
  },
  subscriptions: {
    setupHistory({dispatch, history}) {
      history.listen((location) => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: queryString.parse(location.search),
          },
        })
      })
    },

  },
}
